<template>
  <el-dialog
    :title="data.title"
    :visible.sync="data.visible"
    :before-close="closeDialog"
    :close-on-click-modal="false"
    class="dialog-width"
  >
    <!-- el-form -->
    <el-form :model="data.form" :rules="rules" ref="form" label-width="100px" @submit.native.prevent>
      <el-form-item
        label="连接名称"
        prop="name"
      >
        <el-input
          placeholder="请输入连接名"
          v-model="data.form.name"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="主机IP"
        prop="host"
      >
        <el-input
          placeholder="请输入主机地址"
          v-model="data.form.host"
        >
        </el-input>
      </el-form-item>
      <el-form-item
        label="用户名"
        prop="username"
      >
        <el-input
          placeholder="请输入用户名"
          v-model="data.form.username"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="密码"
        prop="password"
      >
        <el-input
          placeholder="请输入密码"
          v-model="data.form.password"
          show-password
        ></el-input>
      </el-form-item>
      <el-form-item
        label="端口"
        prop="port"
      >
        <el-input
          placeholder="请输入端口"
          v-model="data.form.port"
        ></el-input>
      </el-form-item>

      <el-form-item label="所属分组" prop="parentId">
        <el-select v-model="data.form.parentId" clearable placeholder="请选择分组">
          <el-option
            v-for="item in data.folderData"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <!-- el-form -->
    <span slot="footer">
      <el-button @click="testApiFn" :loading="data.testLoading">
        测试连接
      </el-button>
      <el-button
        type="primary"
        :loading="data.btnLoading"
        @click="submitDialog"
      >
        保存
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
import * as apis from '@/api/fairyshell'
export default {
  data() {
    var validateHost = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入'));
        }else{
          callback()
        }
        //  else {
        //   const regex = /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
        //   if (!regex.test(value)) {
        //     callback(new Error('请输入ip'));
        //   }
        //   callback();
        // }
      };
    return {
      data: {
        title: '新建连接',
        // 默认新增类型
        dialogType: 'add',
        btnLoading: false,
        testLoading: false,
        node: null,
        visible: false,
        folderData:{},
        form: {
          // 名称
          name: '',
          // host
          host: '',
          // 用户名
          username: '',
          // 密码
          password: '',
          // 端口
          port: '22',
          parentId: '',
        },
      },
      rules: {
        name: [
          { required: true, message: '名称不能为空', trigger: 'blur' },
          //{ min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        host: [
          { required: true, message: '请输入主机IP', trigger: 'blur' },
          { validator: validateHost, trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入登录用户', trigger: 'blur' },
          //{ min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
        ],
        port: [
          { required: true, message: '请输入端口', trigger: 'blur' },
        ]
      }
    }
  },
  methods: {
    // 初始化
    init(data) {
      this.data.btnLoading = false
      // form数据先重置
      this.clearDataForm()
      this.data.dialogType = data.flag
      this.data.node = data.value // 新增的父级数据
      this.data.folderData = data.folderData //获取所有分组

      if (data.flag === 'edit') {
        // 编辑
        this.data.title = '编辑连接'
        this.data.form.id = data.value.data.id
        this.data.form.name = data.value.data.name
        this.data.form.host = data.value.data.host
        this.data.form.username = data.value.data.username
        this.data.form.password = data.value.data.password
        this.data.form.port = data.value.data.port
        this.data.form.parentId = data.value.data.parentId
      } else {
        // 新增
        this.data.form.port = 22
        this.data.title = '新建连接'
      }
      this.data.visible = true
    },
    // 确定提交
    submitDialog() {
      this.$refs['form'].validate(valid => {
        this.$nextTick(() => {
          this.data.btnLoading = true
        })
        if (valid) {
          if (this.data.dialogType === 'add') {
            // 新增
            this.addSaveFn()
          } else {
            // 编辑
            this.editSaveFn()
          }
        } else {
          this.$nextTick(() => {
            this.data.btnLoading = false
          })
        }
      })
    },
    // 更新element-ui 局部节点 废弃
    refreshLazyTree(node, children) {
      var theChildren = node.childNodes
      theChildren.splice(0, theChildren.length)
      node.doCreateChildren(children)
    },
    // 新增 => 保存
    addSaveFn() {
      apis
        .treeAdd(this.data.form)
        .then(() => {
          this.$message({
            type: 'success',
            message: '保存成功!'
          })
          // 更新列表
          this.$emit('updateList', this.data.node.data)
        })
        .catch(res => {
          this.$notify.error({
            title: '错误',
            message: (res.data && res.data.mesg) || res.mesg
          })
        })
        .finally(() => {
          this.$nextTick(() => {
            this.data.btnLoading = false
            this.closeDialog()
          })
        })
    },
    // 编辑 => 保存
    editSaveFn() {
      //const form = {...this.data.form,parentId: this.data.form.parentId.length?this.data.form.parentId:0}
      apis
        .update(this.data.form)
        .then(() => {
          this.$message({
            type: 'success',
            message: '更新成功!'
          })
          // 更新列表
          this.$emit('updateList', this.data.node.data)
        })
        .catch(res => {
          this.$notify.error({
            title: '错误',
            message: (res.data && res.data.mesg) || res.mesg
          })
        })
        .finally(() => {
          this.$nextTick(() => {
            this.data.btnLoading = false
            this.closeDialog()
          })
        })
    },
    // 测试连接
    testApiFn () {
      this.data.testLoading = true
      const form = {...this.data.form,parentId: this.data.node && this.data.node.data && this.data.node.data.id ? this.data.node.data.id : '0'}
      apis
        .testConn(form)
        .then((res) => {
           this.$message({
            type: !!res.data ? 'success' : 'error',
            message: !!res.data ? '连接成功' : '连接失败'
          })
        })
        .catch(res => {
          this.$notify.error({
            title: '错误',
            message: (res.data && res.data.mesg) || res.mesg
          })
        })
        .finally(() => {
          this.$nextTick(() => {
            this.data.testLoading = false
          })
        })
    },
    clearDataForm() {
      // 清空数据
      Object.keys(this.data.form).forEach(key => (this.data.form[key] = ''))
    },
    // 取消
    closeDialog() {
      // 弹窗关闭 清除验证
      this.data.visible = false
      // 清空数据
      // this.clearDataForm()
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    }
  }
}
</script>

<style lang="stylus" scoped></style>
